import { loginByPhone, loginByPhoneAndSms, loginByUsername, logout } from '@/api/login'
import { getUser } from '@/api/system/user'
import {
  getToken,
  setToken,
  removeToken,
  setEnterpriseId,
  setSupplierId,
  setWarehouseId,
  setMemberId,
  setUserCode,
  setUserId,
  setUserName,
  setPhone,
  setVersionType,
  setEnterpriseLogoBanner,
  setEnterpriseLogoBannerMini,
  setEnterpriseInfo,
  setEnterpriseConfig,
  setSystemRoleType
} from '@/utils/auth'
import user_avatar from '@/assets/images/user.png'

const user = {
  state: {
    status: '',
    code: '',
    token: getToken(),
    username: '',
    avatar: '',
    roles: []
  },

  mutations: {
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const code = userInfo.code.trim()
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(code, username, userInfo.password).then(response => {
          const data = response.data
          data.code = code
          data.username = username
          setData(data, commit)
          resolve()
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },
    LoginByPhone({ commit }, userInfo) {
      const validateCode = userInfo.validateCode.trim()
      const phone = userInfo.phone.trim()
      return new Promise((resolve, reject) => {
        loginByPhone(phone, userInfo.password, validateCode).then(response => {
          const data = response.data
          if (data.enterpriseName) {
            // 完善资料后才能进入首页
            setData(data, commit)
          }
          resolve(data)
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },
    LoginByPhoneAndSms({ commit }, userInfo) {
      const smsCode = userInfo.smsCode.trim()
      const phone = userInfo.phone.trim()
      return new Promise((resolve, reject) => {
        loginByPhoneAndSms(phone, smsCode).then(response => {
          const data = response.data
          if (data.enterpriseName) {
            // 完善资料后才能进入首页
            setData(data, commit)
          }
          resolve(data)
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },
    LoginByAnonymous({ commit, state }, data) {
      setData(data, commit)
      return new Promise((resolve, reject) => {
        resolve()
      })
    },

    // 获取用户信息
    GetUser({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUser().then(response => {
          if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
            reject('error')
          }
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_USERNAME', data.username)
          let avatar = data.avatar
          // 设置默认头像
          if (!avatar) avatar = user_avatar
          commit('SET_AVATAR', avatar)
          setEnterpriseInfo(data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUser(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_USERNAME', data.username)
          commit('SET_AVATAR', data.avatar)
          setEnterpriseInfo(data)
          resolve()
        })
      })
    }
  }
}

export default user

// 设置登录信息
export const setData = (data, commit) => {
  commit('SET_TOKEN', data.token)
  setToken(data.token)
  setUserId(data.userId)
  setEnterpriseId(data.enterpriseId)
  setEnterpriseConfig(data.enterpriseConfig)
  setSupplierId(data.supplierId ? data.supplierId : '')
  setWarehouseId(data.warehouseId ? data.warehouseId : '')
  setMemberId(data.memberId ? data.memberId : '')
  setVersionType(data.versionType)
  setUserCode(data.userCode)
  setUserName(data.userName)
  setPhone(data.phone)
  setEnterpriseLogoBanner(data.enterpriseLogoBanner)
  setEnterpriseLogoBannerMini(data.enterpriseLogoBannerMini)
  // 系统角色类型 1：企业 2：供应商 3：仓库 4:分销商
  let systemRoleType
  if (data.enterpriseId) {
    systemRoleType = 1
  }
  if (data.supplierId) {
    systemRoleType = 2
  }
  if (data.warehouseId) {
    systemRoleType = 3
  }
  if (data.memberId) {
    systemRoleType = 4
  }
  setSystemRoleType(systemRoleType)
}
